package com.wzh.glsc.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.HttpUtils;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;
import com.wzh.glsc.member.dao.MemberDao;
import com.wzh.glsc.member.dao.MemberWeiBoInfoDao;
import com.wzh.glsc.member.entity.MemberEntity;
import com.wzh.glsc.member.entity.MemberWeiBoInfoEntity;
import com.wzh.glsc.member.exception.PhoneExistException;
import com.wzh.glsc.member.exception.UserNameExistException;
import com.wzh.glsc.member.service.MemberService;
import com.wzh.glsc.member.to.UserLoginTo;
import com.wzh.glsc.member.to.UserRegisterTo;
import com.wzh.glsc.member.to.WeiBoAccessToken;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    MemberWeiBoInfoDao memberWeiBoInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserRegisterTo userRegisterTo)  throws Exception{
        //如果不存在就抛出异常给service,serivce会抛出给调用者
        phoneRepeated(userRegisterTo.getPhone());
        nameRepeated(userRegisterTo.getUserName());
        MemberEntity memberEntity = new MemberEntity();
        // 账号 密码 手机 普通会员
        memberEntity.setUsername(userRegisterTo.getUserName());
        //用Spring提供的MD5对密码进行加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(passwordEncoder.encode(userRegisterTo.getPassword()));
        memberEntity.setMobile(userRegisterTo.getPhone());
        memberEntity.setCreateTime(new Date());
        save(memberEntity);
    }

    @Override
    public void phoneRepeated(String phone) {
        Integer mobileCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        //手机如果存在就抛出手机已存在异常
        if (mobileCount>0){
            throw new PhoneExistException();
        }
    }

    @Override
    public void nameRepeated(String name) {
        Integer userNameCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("userName", name));
        //名字如果存在就抛出名字已存在异常
        if(userNameCount>0){
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginTo userLoginTo) {
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("userName", userLoginTo.getLoginacct())
                .or().eq("mobile", userLoginTo.getLoginacct()).or().eq("email", userLoginTo.getLoginacct()));
        if(memberEntity!=null){
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(userLoginTo.getPassword(), memberEntity.getPassword());
            return matches?memberEntity:null;
        }
        return null;
    }

    @Transactional
    @Override
    public MemberEntity weiboLogin(WeiBoAccessToken weiBoAccessToken) {
        //查询数据是否有登录信息
        MemberWeiBoInfoEntity weiBoInfoEntity = memberWeiBoInfoDao.selectOne(new QueryWrapper<MemberWeiBoInfoEntity>().eq("uid", weiBoAccessToken.getUid()));
        //无论是否有登录过 都要返回MemberEntity
        MemberEntity memberEntity=new MemberEntity();
        if(weiBoInfoEntity!=null){
            //存在就把token更新一下
            weiBoInfoEntity.setAccessToken(weiBoAccessToken.getAccess_token());
            weiBoInfoEntity.setExpiresIn(weiBoAccessToken.getExpires_in());
            memberWeiBoInfoDao.updateById(weiBoInfoEntity);
            //然后查出对应的会员信息
            //TODO 查询数据库时 没有会员数据时 会取不出数据到controller报错
            memberEntity = this.getById(weiBoInfoEntity.getUserId());
        }else{
            //查出用户微博信息  https://api.weibo.com/2/users/show.json  get
            Map<String,String> map=new HashMap<>();
            map.put("access_token" ,weiBoAccessToken.getAccess_token());
            map.put("uid", weiBoAccessToken.getUid());
            try {
                //保存会员信息
                HttpResponse get = HttpUtils.doGet("https://api.weibo.com",
                        "/2/users/show.json", "get",
                        new HashMap<>(), map);
                String json = EntityUtils.toString(get.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                memberEntity.setUsername(jsonObject.getString("name"));
                memberEntity.setGender("m".equals(jsonObject.getString("gender"))?1:0);
                memberEntity.setHeader(jsonObject.getString("profile_image_url"));
                memberEntity.setCreateTime(new Date());
                baseMapper.insert(memberEntity);
                weiBoInfoEntity=new MemberWeiBoInfoEntity();
                weiBoInfoEntity.setUserId(memberEntity.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //TODO 如果保存会员失败没有会员id如果处理
            //保存微博相关信息
            weiBoInfoEntity.setUid(weiBoAccessToken.getUid());
            weiBoInfoEntity.setAccessToken(weiBoAccessToken.getAccess_token());
            weiBoInfoEntity.setExpiresIn(weiBoAccessToken.getExpires_in());
            memberWeiBoInfoDao.insert(weiBoInfoEntity);
        }
        return memberEntity;
    }

}